package cn.uaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/27 17:58
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 安全拦截机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/r/**").authenticated() //所有的请求必须认证通过
                .antMatchers("/r/r1").hasRole("p1")//所有的请求必须认证通过
                .anyRequest().permitAll()  //除了，其它的请求可以访问
                .and()
                .formLogin(); //允许表单登录
                //    //.loginPage("/login-view")
                //    .loginProcessingUrl("/login")
                //    .successForwardUrl("/login-success")
                //.and()
                //.sessionManagement()
                //.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                //.and()
                //.logout()
                //.logoutUrl("/logout")
                //.logoutSuccessUrl("/login-view?logout");
    }

    /**
     * 认证管理器
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
